<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\ProductAftersales;
use app\model\ProductAttributesModel;
use app\model\ProductInformationModel;
use app\model\ProductSalesSpecsModel;
use app\model\ProductShipping;
use app\model\ProductsModel;
use app\model\ProductTimelines;
use app\model\RedisModel;
use app\model\ShopDraftsModel;
use app\model\ShopsModel;
use think\App;
use think\facade\Db;

class Products extends Base {

    protected $middleware = [Auth::class];

    private $aid;

    public $cacheKey="product:id:";

    private $baseCacheKey="product:id:base:";

    private $shopsModel;

    private $productAttributesModel;

    private $productsModel;

    private $productInformationModel;

    private $productSalesSpecsModel;

    private $productTimelines;

    private $productAftersales;

    private $productShippingModel;

    private $req;

    private $shop_id;

    private $shopIds;

    private $page;

    private $limit;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->shop_id = isset($this->req['shop_id']) ? $this->req['shop_id'] : "";

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 20;

        $this->shopsModel = new ShopsModel();

        $this->productAttributesModel = new ProductAttributesModel();

        $this->productsModel = new ProductsModel();

        $this->productInformationModel = new ProductInformationModel();

        $this->productSalesSpecsModel = new ProductSalesSpecsModel();

        $this->productShippingModel = new ProductShipping();

        $this->productTimelines = new ProductTimelines();

        $this->productAftersales = new ProductAftersales();

        $this->shopDraftsModel = new ShopDraftsModel();

        $this->aid = $this->isLogin();

        $this->shopIds = $this->shopsModel->getShopIds($this->aid);

    }

    /*
     * 获取商品列表
     * */
    public function getList(){

        $where=[];
        $where[] = ['p.is_delete',"=",0];
        $where[] = ['p.shop_id','in',$this->shopIds];
        if(!empty($this->req['product_name'])){
            $where[] = ['product_name','like',"%".$this->req['product_name']."%"];
        }
        if(!empty($this->req['product_id'])){
            $where[] = ['p.product_id','=',$this->req['product_id']];
        }
        if(!empty($this->req['category_id'])){
            $where[] = ['p.category_id','=',$this->req['category_id']];
        }
        if(!empty($this->req['shop_name'])){
            $where[] = ['shop_name','like',"%".$this->req['shop_name']."%"];
        }

        if(is_numeric($this->req['product_status']) && in_array($this->req['product_status'],[0,1,-1])){
            $where[] = ['product_status','=',$this->req['product_status']];
        }

        $list = $this->productsModel->getList(2,$where,$this->page,$this->limit,"p.updated_at","DESC");


        $total = $this->productsModel->getTotal($where);


        $this->succData($total,$list);
    }


    /*
     * 获取商品详情
     * */
    public function getInfo(){

        if(empty($this->req['product_id'])){
            return $this->fail("请选择商品");
        }

        $info = $this->productsModel->getInfo($this->req['product_id']);

        if(empty($info)){
            return $this->fail("商品不存在");
        }

        return $this->succ($info);
    }


    /*
 * 添加商品
 * */
    public function add()
    {

        if(mb_strlen($this->req['product_name']) > 40 || empty($this->req['product_name']) ){
            return $this->fail("商品标题不合法");
        }


        if(empty($this->req['shop_id']) || !in_array($this->req['shop_id'],$this->shopIds) ){
            return $this->fail("请选择店铺或则店铺id不正确");
        }

        if(empty($this->req['category_id']) ){
            return $this->fail("请选择类目");
        }


        if(empty($this->req['sales_specs'])){
            return $this->fail("请填写商品规格");
        }

        //处理规格
        $this->req['sales_specs'] = is_array($this->req['sales_specs']) ? $this->req['sales_specs'] : json_decode($this->req['sales_specs'],true);

        foreach ($this->req['sales_specs'] as $key => &$value){

            $num = $key+1;
            if(empty($value['spec_name'])){
                return $this->fail("规格".$num.":请填写商品规格名称");
            }

            if(empty($value['price'])){
                return $this->fail("规格".$num.":请填写商品规格价格");
            }

            if(empty($value['stock'])){
               //return $this->fail("规格".$num.":请填写商品规格库存");
            }

            $value['price'] *= 100;
        }


        if(empty($this->req['timelines_id'])){
            return $this->fail("发货时间不能为空");
        }


        if(empty($this->req['aftersales_options'])){
            return $this->fail("请填写售后选项");
        }


        if(empty($this->req['product_thumbnail'])){
            return $this->fail("商品缩略图不能为空");
        }

        if(empty($this->req['product_pics'])){
            return $this->fail("详情页头图不能为空");
        }


        if(empty($this->req['product_description'])){
            return $this->fail("详情页介绍图不能为空");
        }


        if(empty($this->req['product_type_name']) || !in_array($this->req['product_type_name'],["product","food_therapy"])){
            return $this->fail("商品类型名称只能选择商品或则食疗方");
        }


        Db::startTrans();
        //存储商品
        $prices = array_column($this->req['sales_specs'],"price");
        $product_id = $this->productsModel->insertGetId([
            'product_name' => $this->req['product_name'],
            'shop_id' => $this->req['shop_id'],
            'category_id' => $this->req['category_id'],
            'product_thumbnail' => $this->req['product_thumbnail'],
            'specs_title'=>$this->req["specs_title"],
            'product_pics' => $this->req['product_pics'] ? json_encode($this->req['product_pics'],256) : "",
            'product_description' => json_encode($this->req['product_description'],256),
            'product_max_price' =>max($prices),
            'product_min_price' =>min($prices),
            'product_name_desc' =>$this->req['product_name_desc'],
            'product_type_name' =>$this->req['product_type_name'],
        ]);

        //存储商品属性
        $productAttributesRes = true;
        if(!empty($this->req['product_attributes'])){
            $productAttributesRes =   $this->productAttributesModel->addOne(array_merge([
                'product_id' => $product_id
            ],$this->req['product_attributes']));
        }

        //存储商品信息
        $productInformationRes = true;
        if(!empty($this->req['product_information'])){
            $information = array_merge($this->req['product_information'],[ 'product_id' => $product_id]);
            $productInformationRes =   $this->productInformationModel->save($information);
        }

        //存储规格
        $salesSpecsRes = true;
        if(!empty($this->req['sales_specs'])){
            $salesSpecsList=[];
            $spec_index =0;
            foreach ($this->req['sales_specs'] as  $spec){
                $spec_index ++;
                $one =[];
                $one["spec_id"] = $product_id ."_".$spec_index;
                $one["spec_name"] = $spec['spec_name'];
                $one["product_id"] = $product_id;
                $one["price"] = $spec['price'];
                $one["stock"] = $spec['stock'];
                $salesSpecsList[] =$one;
            }
            $salesSpecsRes =   $this->productSalesSpecsModel->bacthAdd($salesSpecsList);
        }

        //存储商品邮费
        if($this->req["shipping_fee"] > 0){
            $productShippingRes = $this->productShippingModel->save([
                'product_id' => $product_id,
                'shipping_fee' => $this->req["shipping_fee"] * 100,
                'shipping_category' => 2,
                'shipping_name' => "不包邮"
            ]);
        }else{
            $productShippingRes = $this->productShippingModel->save([
                'product_id' => $product_id,
                'shipping_fee' => 0,
                'shipping_category' => 1,
                'shipping_name' => "包邮"
            ]);
        }

        //存储商品售后
        $productAftersalesRes = true;
        if(!empty($this->req['aftersales_options'])){
            $aftersalesList=[];
            foreach ($this->req['aftersales_options'] as $value){
                $aftersalesList[] = [
                    'product_id' => $product_id,
                    'aftersales_option_id' => $value,
                ];
            }
            $productAftersalesRes =   $this->productAftersales->insertAll($aftersalesList);
        }

        //存储发货时间
        $timelinesRes = $this->productTimelines->save([
            'product_id' => $product_id,
            'timelines_id' => $this->req['timelines_id'],
        ]);

        if($product_id && $productAttributesRes && $productInformationRes && $salesSpecsRes && $productShippingRes && $productAftersalesRes && $timelinesRes){

            //清理缓存
            $this->delCache($product_id);

            Db::commit();

            return $this->succ();

        }else{

            Db::rollback();

            return $this->fail();
        }
    }


    /*
     * 修改商品
     * */
    public function edit()
    {
        if(!isset($this->req['product_id']) || empty($this->req['product_id']) ){
            return $this->fail("商品id不能为空");
        }

        $product_id = $this->req['product_id'];

        $productInfo = $this->productsModel->getBaseInfo($product_id);

        if(empty($productInfo)){
            return $this->fail("商品不存在");
        }

        if(mb_strlen($this->req['product_name']) > 40 || empty($this->req['product_name']) ){
            return $this->fail("商品标题不合法");
        }

        if(empty($this->req['shop_id']) || !in_array($this->req['shop_id'],$this->shopIds) ){
            return $this->fail("请选择店铺或则店铺id不正确");
        }

        if(empty($this->req['category_id']) ){
            return $this->fail("请选择类目");
        }

        if(empty($this->req['sales_specs'])){
            return $this->fail("请填写商品规格");
        }

        //处理规格
        foreach ($this->req['sales_specs'] as $key => &$value){

            $num = $key+1;

            if(empty($value['spec_name'])){
                return $this->fail("规格".$num.":请填写商品规格名称");
            }

            if(empty($value['price'])){
                return $this->fail("规格".$num.":请填写商品规格价格");
            }

            if(empty($value['stock'])){
               // return $this->fail("规格".$num.":请填写商品规格库存");
            }

            $value['price'] *= 100;
        }


        if(empty($this->req['timelines_id'])){
            return $this->fail("发货时间不能为空");
        }


        if(empty($this->req['aftersales_options'])){
            return $this->fail("请填写售后选项");
        }


        if(empty($this->req['product_thumbnail'])){
            return $this->fail("商品缩略图不能为空");
        }

        if(empty($this->req['product_pics'])){
            return $this->fail("详情页头图不能为空");
        }


        if(empty($this->req['product_description'])){
            return $this->fail("详情页介绍图不能为空");
        }


        if(empty($this->req['product_type_name']) || !in_array($this->req['product_type_name'],["product","food_therapy"])){
            return $this->fail("商品类型名称只能选择商品或则食疗方");
        }


        Db::startTrans();
        //存储商品
        $prices = array_column($this->req['sales_specs'],"price");

        $updateProductRes = $this->productsModel->where("product_id","=",$product_id)->update([
            'product_name' => $this->req['product_name'],
            'shop_id' => $this->req['shop_id'],
            'category_id' => $this->req['category_id'],
            'product_thumbnail' => $this->req['product_thumbnail'],
            'product_pics' => $this->req['product_pics'] ? json_encode($this->req['product_pics'],256) : "",
            'product_description' => json_encode($this->req['product_description'],256),
            'specs_title'=>$this->req["specs_title"],
            'product_max_price' =>max($prices),
            'product_min_price' =>min($prices),
            'product_name_desc' =>$this->req['product_name_desc'],
            'product_type_name' =>$this->req['product_type_name'],
            'updated_at'=>date("Y-m-d H:i:s")
        ]);


        //存储商品属性
        $productAttributesRes = true;
        if(!empty($this->req['product_attributes'])){
            //删除商品的所有属性
            $this->productAttributesModel->delAllProductAttributes($product_id);

            $productAttributesRes =   $this->productAttributesModel->addOne(array_merge([
                'product_id' => $product_id
            ],$this->req['product_attributes']));
        }

        //存储商品信息
        $productInformationRes = true;
        if(!empty($this->req['product_information'])){
            //删除商品信息
            $this->productInformationModel->delAllProductInformation($product_id);
            //重新添加商品信息
            $information = array_merge($this->req['product_information'],['product_id' => $product_id]);

            $productInformationRes =   $this->productInformationModel->save($information);
        }

        //存储规格
        $salesSpecsRes = true;
        if(!empty($this->req['sales_specs'])){
            $salesSpecsList=[];
            $spec_index =0;
            foreach ($this->req['sales_specs'] as  $spec){
                $spec_index ++;
                $one =[];
                $one["spec_id"] = $product_id ."_".$spec_index;
                $one["spec_name"] = $spec['spec_name'];
                $one["product_id"] = $product_id;
                $one["price"] = $spec['price'];
                $one["stock"] = $spec['stock'];
                $salesSpecsList[] =$one;
            }

            //var_dump($salesSpecsList);die;
            //删除商品规格
            $this->productSalesSpecsModel->delAllProductSalesSpecs($product_id);
            //重新添加规格
            $salesSpecsRes =   $this->productSalesSpecsModel->bacthAdd($salesSpecsList);
        }


        //删除商品邮费
        $this->productShippingModel->delProductShipping($product_id);
        //存储商品邮费
        if($this->req["shipping_fee"] > 0){
            $productShippingRes = $this->productShippingModel->save([
                'product_id' => $product_id,
                'shipping_fee' => $this->req["shipping_fee"] * 100,
                'shipping_category' => 2,
                'shipping_name' => "不包邮"
            ]);
        }else{
            $productShippingRes = $this->productShippingModel->save([
                'product_id' => $product_id,
                'shipping_fee' => 0,
                'shipping_category' => 1,
                'shipping_name' => "包邮"
            ]);
        }

        //存储商品售后
        $productAftersalesRes = true;
        if(!empty($this->req['aftersales_options'])){
            $aftersalesList=[];
            foreach ($this->req['aftersales_options'] as $value){
                $aftersalesList[] = [
                    'product_id' => $product_id,
                    'aftersales_option_id' => $value,
                ];
            }

            //删除商品售后属性
            $this->productAftersales->delAllProductAftersales($product_id);
            //重新添加商品售后属性
            $productAftersalesRes =   $this->productAftersales->insertAll($aftersalesList);
        }

        //存储商品发货时间
        $this->productTimelines->delProductTimelines($product_id);
        //存储发货时间
        $timelinesRes = $this->productTimelines->save([
            'product_id' => $product_id,
            'timelines_id' => $this->req['timelines_id'],
        ]);

        if($updateProductRes && $productAttributesRes && $productInformationRes && $salesSpecsRes && $productShippingRes && $productAftersalesRes && $timelinesRes){

            $this->delCache($product_id);

            Db::commit();

            return $this->succ();
       }else{

            Db::rollback();

           return $this->fail();
       }
    }


    /*
  * 修改商品
  * */
    public function updateProductStatus()
    {
        if (!isset($this->req['product_id']) || empty($this->req['product_id'])) {
            return $this->fail("商品id不能为空");
        }

        $product_id = $this->req['product_id'];

        $productInfo = $this->productsModel->getBaseInfo($product_id);

        if (empty($productInfo)) {
            return $this->fail("商品不存在");
        }

        $where=[];
        $where[] = ["product_id","=",$product_id];
        $res = $this->productsModel->updateAll($where,[
            "product_status"=>$this->req['product_status']
        ]);

        if($res){

            $this->delCache($product_id);

            return $this->succ();

        }else{

            return $this->succ();

        }

    }

    /*
     * 删除商品
     * */
    public function delProduct()
    {
        if (!isset($this->req['product_id']) || empty($this->req['product_id'])) {
            return $this->fail("商品id不能为空");
        }

        $product_id = $this->req['product_id'];

        $productInfo = $this->productsModel->getBaseInfo($product_id);

        if (empty($productInfo)) {
            return $this->fail("商品不存在");
        }

        $where=[];
        $where[] = ["product_id","=",$product_id];
        $res = $this->productsModel->updateAll($where,[
            "is_delete"=>1
        ]);

        $this->delCache($product_id);

        if($res){

            return $this->succ();

        }else{

            return $this->succ();

        }

    }





    public function delCache($id)
    {
        $redisModel = new RedisModel();

        //删除商品缓存
        $redisModel->delete($this->cacheKey.$id);

        $redisModel->delete($this->baseCacheKey.$id);

        //删除商品属性缓存
        $this->productAttributesModel->delProductAttributesCache($id);
        //删除商品规格缓存
        $this->productSalesSpecsModel->delProductSalesSpecsCache($id);
        //删除商品信息缓存
        $this->productInformationModel->delProductInformationCache($id);
        //删除商品快递信息缓存
        $this->productShippingModel->delProductShippingCache($id);
        //删除商品时效缓存
        $this->productTimelines->delProductTimelinesCache($id);

        return true;

    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        $redisModel->deleteAll($this->cacheKey);

        //删除全部商品属性缓存
        $this->productAttributesModel->delAllProductAttributesCache();
        //删除全部商品规格缓存
        $this->productSalesSpecsModel->delAllProductSalesSpecsCache();
        //删除全部商品信息缓存
        $this->productInformationModel->delAllProductInformationCache();
        //删除全部商品快递信息缓存
        $this->productShippingModel->delAllProductShippingCache();
        //删除全部商品时效缓存
        $this->productTimelines->delAllProductTimelinesCache();

        return true;
    }

}
